<?php

	try{
		
		if( isset( $_GET['logout'] ) ){
			
			session_unset(); 
			$_SESSION = array();
			$loggedin = false;
			
		}
		
		if( isset($_SESSION['user']) && $_SESSION['user'] != "" ){

			$loggedin = true;
		
		}else{
		
			if( isset( $_POST['btn_login'] ) ){
				
				if( isset( $_POST['login_user'] ) && $_POST['login_user'] != "" ) $login_user = trim( $_POST['login_user'] );
									
				if( isset( $_POST['login_pass'] ) && $_POST['login_pass'] != "" ) $login_pass = md5( trim( $_POST['login_pass'] ) );
				
				$db = @new mysqli( $db_host,$db_user,$db_pass,$db_name );
				
				if ( !mysqli_connect_errno() ){
				
					$sql = "SELECT * FROM `system_benutzer` WHERE `name` = '$login_user'";
				    $users = $db->query( $sql );
				    
				    if( $users->num_rows > 0 ){
						    	
						while( $user = $users->fetch_object() ){
					
							if($user->passwort == $login_pass){
								
								$_SESSION['user'] = $login_user;
								$_SESSION['pass'] = $user->passwort;
								$_SESSION['vname'] = $user->vorname;
								$_SESSION['nname'] = $user->nachname;
								$_SESSION['gid'] = $user->gruppenid;
								$_SESSION['uid'] = $user->id;
								$loggedin = true;
								
							}else{
																				  	
								$_SESSION = array();
								session_unset();
								session_destroy();
								$loggedin = false;
								
							}
							
						}

					}else{
						  			    
						throw new Exception( 'Die Abfrage '.$sql.' liefert keine Ergebnisse' );
						
					}
				    
					$users->close();
				    
				}else{
					
					throw new Exception( 'Die Datenbank konnte nicht erreicht werden. Folgender Fehler trat auf: <strong>' .mysqli_connect_errno(). ' : ' .mysqli_connect_error(). '</strong>' );
					  
				}
				
				$db->close();
				
			}else{
				
				$loggedin = false;
				
			}
				
		}

	}catch( Exception $e ){
		
		echo '<pre><b>Exception</b>'."\n"; 
		echo $e->getMessage();
		echo '</pre>';
		   
	}
	
	if($loggedin){
		
		$output = "\t\t\t".'<p>'."\n";
		$output.= "\t\t\t\t".'<b>'.$_SESSION['user'].'</b> | '."\n";
		$output.= "\t\t\t\t".'<a href="index.php?logout">logout</a>'."\n";
		$output.= "\t\t\t".'</p>'."\n";
		
	}else{
		
		$output = "\t\t\t".'<form action="'.$_SERVER['PHP_SELF'].'" method="post">'."\n";
		$output.= "\t\t\t\t".'<p>'."\n";
		$output.= "\t\t\t\t\t".'Login'."\n";
		$output.= "\t\t\t\t\t".'<input type="text" name="login_user" id="login_user" class="input_txt" />'."\n";
		$output.= "\t\t\t\t\t".'<input type="password" name="login_pass" id="login_pass" class="input_txt" />'."\n";
		$output.= "\t\t\t\t\t".'<input type="submit" name="btn_login" id="btn_login" class="input_btn" value="login" />'."\n";
		$output.= "\t\t\t\t".'</p>'."\n";
		$output.= "\t\t\t".'</form>'."\n";
		
	}

	echo $output;